<template>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 条件查询 -->
    <el-card class="queryFormElCard mt-4">
        <el-form :model="queryParam" ref="queryFromRef">
            <el-row>
                <el-col :span="4">
                    <el-form-item label="部门">
                        <el-tree-select v-model="queryParam.deptId" placeholder="请选择部门" :data="deptList"
                        :props="deptTreeProps" check-strictly :clearable="true" :filterable="true"
                        :render-after-expand="false" default-expand-all />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="用户名">
                        <el-input v-model="queryParam.username" placeholder="请输入用户名" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="真实姓名">
                        <el-input v-model="queryParam.realName" placeholder="请输入真实姓名" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="手机号">
                        <el-input v-model="queryParam.phone" placeholder="请输入手机号" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-space class="ml-2">
                        <el-button plain type="primary" :icon="Search" @click="querySelective">查询</el-button>
                        <el-button plain :icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-space>
                </el-col>
            </el-row>
        </el-form>
    </el-card>
    <!-- 表格、分页 -->
    <el-card>
        <el-space class="mb-4">
            <el-button plain type="primary" :icon="CirclePlus" @click="showAddOrUpdatePage('add', null)"
                v-perm="['sys:user:add']">添加</el-button>
            <el-button plain type="danger" :icon="Delete" @click="batchDelete"
                v-perm="['sys:user:delete']">删除</el-button>
        </el-space>
        <el-table :data="tableData" border :header-cell-style="{ 'background': '#f2f2f2', 'color': '#515a6e' }"
            style="width: 100%" height="calc(100vh - 310px)" max-height="calc(100vh - 310px)" row-key="id"
            @selection-change="handleSelectionChange" v-loading="tableLoading">
            <el-table-column type="selection" width="55px" />
            <el-table-column prop="username" label="用户名" width="120px" />
            <el-table-column prop="realName" label="真实姓名" width="120px" />
            <el-table-column prop="phone" label="手机号" width="130px" />
            <el-table-column prop="email" label="邮箱" width="200px" />
            <el-table-column label="性别" width="70px">
                <template #default="scope">
                    <el-tag :type="getCssByValue(userSexList,scope.row.sex)">{{getKeyByValue(userSexList,scope.row.sex)}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="部门" width="150px" show-overflow-tooltip>
                <template #default="scope">
                    {{ scope.row.sysDeptTree ? scope.row.sysDeptTree.map(user => formatDept(scope.row.sysDeptTree[0]))[0] : ''}}
                </template>
            </el-table-column>
            <el-table-column label="岗位" width="150px">
                <template #default="scope">
                    <p>{{ scope.row.sysPost?.name }}</p>
                </template>
            </el-table-column>
            <el-table-column label="角色">
                <template #default="scope">
                    <p>{{ scope.row.sysRoles?.map(item => item.name).join(',') }}</p>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="250px" fixed="right">
                <template #default="scope">
                    <el-space>
                        <el-button link type="warning" size="small" :icon="EditPen"
                            @click="showAddOrUpdatePage('update', scope.row)"
                            v-perm="['sys:user:update']" v-if="scope.row.id != 1">修改</el-button>

                        <el-button link type="danger" size="small" :icon="Delete" @click="deleteById(scope.row)"
                            v-perm="['sys:user:delete']" v-if="scope.row.id != 1">删除</el-button>

                        <el-button link type="danger" size="small" :icon="Star" @click="resetPassword(scope.row)"
                            v-perm="['sys:user:resetPassword']">重置密码</el-button>
                    </el-space>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="currentPageNum" v-model:page-size="currentPageSize"
            :page-sizes="[30, 50, 100, 300, 500]" layout="total, sizes, prev, pager, next, jumper" background
            :total="totalCount" @size-change="changePageSize" @current-change="changePageNum" />
    </el-card>
    <AddOrUpdate ref="addOrUpdatePageRef" :querySelective="querySelective" :deptList="deptList" :deptTreeProps="deptTreeProps"></AddOrUpdate>
</template>

<script setup>
import { onMounted, ref, reactive, watch } from "vue"
import { CirclePlus, Delete, Refresh, Search, EditPen, Star } from '@element-plus/icons-vue'
import { querySelectiveReq, deleteReq, resetPasswordReq } from '@/api/sys/user/index.js'
import { queryDeptAllTreeReq } from "@/api/sys/dept/index.js"

import { confirm } from '@/utils/messageBoxUtils.js'
import { success, info } from '@/utils/messageUtils.js';

import AddOrUpdate from "@/views/sys/user/AddOrUpdate.vue";

import { queryDataListByTypeReq } from "@/api/sys/dict/data/index.js"
import {getKeyByValue,getCssByValue} from '@/utils/dict.js';

const deptTreeProps = ref({
    children: 'children',
    label: 'name',
    value: 'id'
})
const deptList = ref([])
const userSexList = ref([])
onMounted(() => {
    Promise.all([
        queryDeptAllTreeReq(),
        queryDataListByTypeReq('user_sex')
    ]).then(([deptListRes, userSexDictRes
    ]) => {
        deptList.value = deptListRes.data;
        userSexList.value = userSexDictRes.data;
        querySelective();
    });
})

// 条件查询
const queryParam = reactive({
    username: '',
    realName: '',
    phone: '',
    deptId: null
})
const queryFromRef = ref()
const resetQuery = () => {
    queryParam.username = ''
    queryParam.realName = ''
    queryParam.phone = ''
    queryParam.deptId = null
    queryFromRef.value?.resetFields();
    currentPageNum.value = 1
    querySelective();
}

// 分页查询、条件查询
const tableLoading = ref(false)
const tableData = ref([])
const total = ref()
const querySelective = () => {
    tableLoading.value = true;
    querySelectiveReq(
        currentPageNum.value,
        currentPageSize.value,
        {
            username: queryParam.username ? queryParam.username : '',
            realName: queryParam.realName ? queryParam.realName : '',
            phone: queryParam.phone ? queryParam.phone : '',
            deptId: queryParam.deptId ? queryParam.deptId : null,
        }
    ).then(res => {
        if (res.code == 200) {
            tableData.value = res.data
            total.value = res.total
        }
    }).finally(() => {
        tableLoading.value = false
    })
}
const totalCount = ref(0)
watch(() => total.value, (newValue) => {
    totalCount.value = newValue;
});

const currentPageNum = ref(1)
const currentPageSize = ref(30)
// 翻页
const changePageNum = (pageNum) => {
    currentPageNum.value = pageNum
    querySelective();
}
// 改变页大小
const changePageSize = (pageSize) => {
    currentPageNum.value = 1
    currentPageSize.value = pageSize
    querySelective();
}

// 删除
const deleteById = (row) => {
    const ids = []
    ids.push(row.id)
    confirm("您确定删除\"" + row.realName + "\"用户吗？").then(() => {
        deleteReq(ids).then(res => {
            if (res.code == 200) {
                querySelective();
                success("删除" + row.realName + "用户成功！");
            }
        })
    }).catch(() => {
        info("取消删除！");
    })
}

// 重置密码
const resetPassword = (row) => {
    confirm("您确定重置\"" + row.realName + "\"用户的密码吗？").then(() => {
        resetPasswordReq(row.id).then(res => {
            if (res.code == 200) {
                success("重置" + row.realName + "用户的密码为123456");
            }
        })
    }).catch(() => {
        info("取消删除！");
    })
}

// 批量操作
const selectIds = ref([])
const handleSelectionChange = (val) => {
    selectIds.value = []
    val.forEach(item => {
        selectIds.value.push(item.id)
    })
}

// 批量删除
const batchDelete = () => {
    confirm("您确定删除选中的用户吗？").then(() => {
        deleteReq(selectIds.value).then(res => {
            if (res.code == 200) {
                querySelective();
                success("删除成功！");
            }
        })
    }).catch(() => {
        info("取消删除！");
    })
}

// 添加
const addOrUpdatePageRef = ref()
const showAddOrUpdatePage = (type, row) => {
    addOrUpdatePageRef.value?.open(type, row)
}

// 格式化部门树
const formatDept = (dept) => {
    if (!dept) return '';
    let result = dept.name;
    if (dept.children && dept.children.length > 0) {
        const childrenNames = dept.children.map(child => formatDept(child));
        result += ' - ' + childrenNames.join(' - ');
    }
    return result;
}
</script>

<style>
.queryFormElCard .el-card__body {
    padding-bottom: 0;
}
</style>